package com.hup.sidebar.view;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.hup.sidebar.R;
import com.hup.sidebar.SideBarApplication;
import com.hup.sidebar.constant.PieFunctionConstant;
import com.hup.sidebar.framework.util.ListUtil;
import com.hup.sidebar.framework.util.SpUtil;
import com.hup.sidebar.framework.view.BaseAdapter;
import com.hup.sidebar.framework.view.BaseViewHolder;
import com.hup.sidebar.model.AppConfig;
import com.hup.sidebar.model.MultiPieFunction;
import com.hup.sidebar.model.PieFunction;
import com.hup.sidebar.service.ActivationFloaterService;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 功能设置
 * 设置全部扇区的功能
 *
 * @author hugan
 * @date 2022/6/6
 */
@SuppressLint("NonConstantResourceId")
public class PieFunctionActivity extends AppCompatActivity implements OnClickListener {
    private static final String TAG = PieFunctionActivity.class.getSimpleName();


    @BindView(R.id.listView)
    ListView listView;

    /**
     * 数据对象是 appConfig中的数据!
     */
    private PieFunctionAdapter adapter;
    private AppConfig appConfig;

    /**
     * (跳转到选择功能界面后),当前要设置的功能的index
     */
    private int currentSettingIndex;
    /**
     * (跳转到选择功能界面后),当前要设置的功能:短按/长按
     */
    private boolean currentSettingNormal;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        appConfig = SideBarApplication.getBean(AppConfig.class);
        currentSettingIndex = 0;

        initView();
    }

    private void initView() {
        setContentView(R.layout.pie_function_activity);
        ButterKnife.bind(this);

        adapter = new PieFunctionAdapter(this);
        adapter.setData(appConfig.functions);
        listView.setAdapter(adapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.pie_function_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.menu_add) {
            Log.d(TAG, "onOptionsItemSelected: add");
            MultiPieFunction multiPieFunction = new MultiPieFunction();
            adapter.addLastItem(multiPieFunction);
            appConfig.functions.add(multiPieFunction);
            saveAppConfig();
        }
        return true;
    }

    /**
     * item按钮监听
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();
        int position = (int) v.getTag();
        Log.i(TAG, "onClick: id=" + id + ", tag=" + position);

        //编辑功能列表,会更新AppConfig的数据
        if (id == R.id.btnFunction || id == R.id.btnLongFunction) {
            currentSettingIndex = position;
            currentSettingNormal = id == R.id.btnFunction;
            MultiPieFunction multiPieFunction = adapter.getItem(position);
            PieFunction function = currentSettingNormal ? multiPieFunction.normal : multiPieFunction.longPress;
            SelectFunctionActivity.startActivityForResult(this, function);
        } else {
            if (id == R.id.btnUp) {
                if (position < 1) return;
                ListUtil.swap((ArrayList<?>) adapter.getData(), position, position - 1);
                adapter.notifyDataSetChanged();
                ListUtil.swap(appConfig.functions, position, position - 1);
            } else if (id == R.id.btnDown) {
                ArrayList<?> data = (ArrayList<?>) adapter.getData();
                if (position > data.size() - 2) return;
                ListUtil.swap(data, position, position + 1);
                adapter.notifyDataSetChanged();
                ListUtil.swap(appConfig.functions, position, position + 1);
            } else if (id == R.id.btnDelete) {
                adapter.removeItem(position);
                MultiPieFunction removed = appConfig.functions.remove(position);
                PieFunctionConstant.releaseIcon(removed.normal);
                PieFunctionConstant.releaseIcon(removed.longPress);
            }
            saveAppConfig();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(TAG, "onActivityResult: " + requestCode + ", " + resultCode);
        if (requestCode == SelectFunctionActivity.REQUEST_CODE) {
            PieFunction result = SelectFunctionActivity.handleActivityResult(this, requestCode, resultCode);

            if (result == null) return;//取消选择
            if (result.type == PieFunctionConstant.TYPE_NONE) {
                result = null;//TYPE_NONE时,功能对象是null
            }
            Log.i(TAG, "onActivityResult.设置功能: " + result);

            //刷新全局图标
            PieFunctionConstant.updateCachedIcon(SideBarApplication.getContext(), result, appConfig);
            //此处的multiPieFunction 与appConfig的function是同一个对象,所以不用写appConfig
            MultiPieFunction multiPieFunction = adapter.getItem(currentSettingIndex);
            if (currentSettingNormal) {
                PieFunctionConstant.releaseIcon(multiPieFunction.normal);
                multiPieFunction.setNormal(result);
            } else {
                PieFunctionConstant.releaseIcon(multiPieFunction.longPress);
                multiPieFunction.setLongPress(result);
            }
            adapter.notifyDataSetChanged();
            saveAppConfig();
        }
    }

    /**
     * 保存配置
     */
    private void saveAppConfig() {
        String str = JSON.toJSONString(adapter.getData());
        Log.i(TAG, "saveAppConfig: " + str);
        SpUtil.apply(appConfig.getSp(this), "functions", str);
        SideBarApplication.executeIfExist(ActivationFloaterService.class, ActivationFloaterService::onPieConfigUpdated);
    }

    private static class PieFunctionAdapter extends BaseAdapter<MultiPieFunction, PieFunctionViewHolder> {

        private final PieFunctionActivity activity;

        public PieFunctionAdapter(PieFunctionActivity activity) {
            this.activity = activity;
        }

        @Override
        public int getLayoutResId() {
            return R.layout.pie_function_item;
        }

        @Override
        public PieFunctionViewHolder createHolder() {
            return new PieFunctionViewHolder(activity);
        }

    }

    public static class PieFunctionViewHolder implements BaseViewHolder<MultiPieFunction> {

        @BindView(R.id.btnFunction)
        ImageView btnFunction;
        @BindView(R.id.btnLongFunction)
        ImageView btnLongFunction;
        @BindView(R.id.btnUp)
        ImageView btnUp;
        @BindView(R.id.btnDown)
        ImageView btnDown;
        @BindView(R.id.btnDelete)
        ImageView btnDelete;

        private final PieFunctionActivity activity;

        public PieFunctionViewHolder(PieFunctionActivity activity) {
            this.activity = activity;
        }

        @Override
        public void onBindView(View view) {
            btnFunction.setOnClickListener(activity);
            btnLongFunction.setOnClickListener(activity);
            btnUp.setOnClickListener(activity);
            btnDown.setOnClickListener(activity);
            btnDelete.setOnClickListener(activity);
        }

        @Override
        public void bindData(int position, MultiPieFunction item) {
            //Log.i(TAG, "bindData: " + position + ", " + item);
            btnFunction.setTag(position);
            btnLongFunction.setTag(position);
            btnUp.setTag(position);
            btnDown.setTag(position);
            btnDelete.setTag(position);

            btnFunction.setImageBitmap(getIcon(item.normal));
            btnLongFunction.setImageBitmap(getIcon(item.longPress));
        }

        private Bitmap getIcon(PieFunction function) {
            if (function == null) return null;
            return function.cachedIcon;
        }
    }

}
